<?php
class Task_daily extends Task{
	public $task_id;
	public $ruleDB;
	public function Task_daily($task_id=''){
		$this->task_id=$task_id;
		$this->initialize();
		$this->ruleDB=M('integral_rule');//规则表
	}
	//点击确认完成的方法（更改任务状态）  ->  若状态为 1/‘完成’ 那么触发相应的事件
	public function changeStatus($id='',$status=3){
		$map['id']=''==$id?$this->task_id:$id;
		$result=$this->taskDB->where($map)->setField(['status'=>$status]);
		if(false==$result){
			$this->error=$this->taskDB->getDbError();
			return false;
		}else{
			$this->newProgress(['task_id'=>$id,'remark'=>'任务状态改变为：'.$status]);
			
			return $result;
		}
	}
	
	//固定任务检测并产生数据
	public function fixTaskData($id=''){
		$id=''==$id?session(C('USER_AUTH_KEY')):$id;
		$map['member_id']=$id;
		$map['loop_id']=1;
		$map['site_id']=__SITEID__;	
		$map['realtime']=array('LT',strtotime(date('Y-m-d 0:0:1',time())));
		$task=$this->taskDB->where($map)->select();
		if(false==$task){return false;}
		else{
			$arr=[];
			foreach($task as $val){
				$rule_id=explode(',',$val['rule_id']);
				$ar=[];
				foreach($rule_id as $va){
					$ar[]=$this->ruleDB->where(['id'=>$va])->find();
				}
				$arr[]=['id'=>$val['id'],'name'=>$val['title'],'rule_id'=>$val['rule_id'],'rule'=>$ar];
			}
			return $arr;	
		}
	}
	
	//递龟查询出上级的任务ID
	public function finalTask($id){
		$pid=$this->taskDB->where(['id'=>$id])->getField('pid');
		if($pid==='0'){
			return $id;	
		}else{
			return $this->finalTask($pid);	
		}
	}
	
	public function taskDone($data=''){
		$data=''==$data?$_REQUEST:$data; //数据源
		$rule_ids=$data['rule_ids'];	//该任务中的所有规则ID
		
		//将确认完成的规则的状态存至任务扩展表中
		$data2['task_id']=$data['id'];
		$data2['name']='status';
		$data2['value']=serialize($data['rule_id']);
		$result=$this->extendsDB->add($data2);
		if(false==$result){
			$this->error=$this->task_id->getDbError();
			return false;
		}
		
		//先循环提交上来的规则ID
		foreach($data['rule_id'] as $val){
			$rule_ids=str_replace($val,'',$rule_ids);
			$rule_data=$this->ruleDB->where(['id'=>$val])->select();
		}
		//再循环剩余的规则
		$rule_ids=explode(',',$rule_ids);
		foreach($rule_ids as $val){
			$rule_data=$this->ruleDB->where(['id'=>$val])->select();	
		}
		
		
		//改变任务状态
		$result=$this->taskDB->where(['id'=>$data['id']])->setField(['status'=>1,'realtime'=>time()]);
		if(false==$result){
			$this->error=$this->task_id->getDbError();
			return false;
		}
		
		//加分（待定)
		return true;
	}
	
	//将循环的任务的状态重新恢复
	public function taskLoop(){
		$this->taskDB->Field(['loop_id'=>1])->setField('status',0);	
	}
	
	//通过筛选得出任务列表
	
    public function _list($view,$map,$pagesize=20) {
		//计算总页数
		$count = $this->taskDB->where($map)->count();
		import('ORG.Util.Page');//实例化分页类
		$p = new Page($count, $pagesize);
		$list = $this->taskDB->where($map)->limit($p->firstRow . ',' . $p->listRows)->select();
		$pages = $p->show();
		$_GET['list']=$list;
		$view->assign('list',$list);
		$view->assign('pages',$pages);
    }
	public function filter($map=array()){
		//筛选是否和自己有关
		$where['member_id']=session(C('USER_AUTH_KEY'));
		$where['creator_id']=session(C('USER_AUTH_KEY'));
		$where['executor_id']=session(C('USER_AUTH_KEY'));
		$where['follower_id']=session(C('USER_AUTH_KEY'));
		$where['reviewer_id']=session(C('USER_AUTH_KEY'));
		$where['_logic']='or';
		$map['_complex']=$where;
		//搜索标题
		if(!empty($_REQUEST['keywords'])){
			$map['title']=array('like','%'.$_REQUEST['keywords'].'%');
		}
        //筛选开始时间与结束时间
        if(trim($_REQUEST['starttime'])!=''){
            $map['time']=array('GT',strtotime($_REQUEST['starttime']));
        }
        if(trim($_REQUEST['endtime'])!=''){
            $map['time']=array('LT',strtotime($_REQUEST['endtime']));
        }
        if(""==trim($_REQUEST['starttime'])&&""==trim($_REQUEST['endtime'])){
            $map['time']=array('GT',strtotime("-1 month"));
        }
        if(""!=trim($_REQUEST['starttime'])&&""!=trim($_REQUEST['endtime'])){
            $map['time']=array('between',array(strtotime($_REQUEST['starttime']),strtotime($_REQUEST['endtime'])));
        }
        //筛选某个职员 或一整个部门
        if(""!=trim($_REQUEST['member_id'])){
            //$map['member_id']=$_REQUEST['member_id'];    
        }
		//筛选状态
		if(''!=trim($_REQUEST['status'])){
			$map['status']=$_REQUEST['status'];
		}
		//筛选父类
		if(''!=trim($_REQUEST['pid'])){
			$map['pid']=$_REQUEST['pid'];
		}
		
        $map['site_id']=__SITEID__;
		
		return $map;
	}
	
	//任务主页
	public function taskIndex($view){
		//$this->_list($view,$this->filter(['pid'=>0]));
		
       //获取 筛选或添加 所需型，部门，所有员工等数据
       /*$view->assign('grouplist',D('Member_group')->getGroup());
	   $view->assign('ruletypelist',D('Integral_ruletype')->getRuletype(0));
       $view->assign('memberlist',D('Member')->getallgroupmember2());*/
	}
	
	//重写插入方法(跟据member_id)
	public function insert_daily(){
		$_POST['site_id'] = __SITEID__;
		$_POST['creator_id']=session ( C ( 'USER_AUTH_KEY' ));
		$_POST['creator_name']=session ( 'loginUserName');
		$_POST['remark']=strip_tags($_POST['remark']);
		$_POST['datetime']=time();
		$_POST['status']=1;
		$_POST['form_id']=is_array($_POST['form_id'])?implode(',',$_POST['form_id']):$_POST['form_id'];
		$_POST['rule_id']=is_array($_POST['rule_id'])?implode(',',$_POST['rule_id']):$_POST['rule_id'];
		$_POST['rule_name']=is_array($_POST['rule_name'])?implode(',',$_POST['rule_name']):$_POST['rule_name'];
		
		//循环遍历会员ID插入数据
		$memberid=isset($_POST['member_id'])?explode(',',$_POST['member_id']):[session(C('USER_AUTH_KEY'))];
		$membername=isset($_POST['member_name'])?explode(',',$_POST['member_name']):[session('memberInfo')['name']];
		foreach($memberid as $k=>$va){
			if(''==trim($va)){continue;}
			$_POST['member_id']=(int)$va;
			$_POST['member_name']=$membername[$k];
			$result=$this->insert();
			if(!$result){ return false;}
		}
		return true;
	}
	
	//任务分发,接受人员ID和任务ID
	public function distribution(){
		$info=$this->getInfo($_POST['task_id']);
		$memberid=$_POST['member_id'];
		$membername=$_POST['member_name'];
		foreach($info as $k=>$v){
			$_POST[$k]=$v;
		}
		$_POST['datatime']=time();
		//$_POST['pid']=$_POST['id'];
		unset($_POST['id'],$_POST['progress_remark'],$_POST['progresstime']);
		foreach($memberid as $k=>$v){
			$_POST['member_name']=$membername[$k];
			$_POST['member_id']=$v;
			if(!$this->insert()){return false;}
		}
		return true;
	}
	
	public function groupStatu(){
		$list=$this->taskDB->where($this->filter())->group('status')->Field('status,count(id) as count')->select();
		return $list;
	}
}